<template>
    <div>
        <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
            :before-close="handleClose" destroy-on-close draggable>
            <template #header="{ close }">
                <div class="dialog-header flex justify-between items-center">
                    <div>意见汇总</div>
                    <el-icon class="el-icon--left cursor-pointer" @click="close">
                        <CircleCloseFilled color="#fff" />
                    </el-icon>
                </div>
            </template>
            <!-- 评分详情 -->
            <div class="bg-white mt-[10px]">
                <BaseHead>评分详情</BaseHead>
                <div class="p-[10px]">
                    <el-descriptions title="" :column="2" border label-width="140">
                        <el-descriptions-item label-class-name="gdlable" label="获奖名称">{{
            ruleForm.honorName
        }}</el-descriptions-item>
                    </el-descriptions>
                    <el-table :data="reviewTableData" stripe max-height="360" style="width: 100%">
                        <el-table-column header-align="center" label="标准">
                            <el-table-column prop="name" header-align="center" label="标准名称" />
                            <el-table-column prop="standardMark" header-align="center" label="满分" />
                        </el-table-column>
                        <el-table-column label="专家评分详情" header-align="center">
                            <el-table-column v-for="(item, index) in ruleForm.allExpertReviewVOS" :key="index"
                                header-align="center" :label="item.reviewerName">
                                <template #default="scope">
                                    {{
            item.reviewResultVOs &&
                item.reviewResultVOs.length ?
                item.reviewResultVOs[scope.$index].reviewMark : ''
        }}</template>
                            </el-table-column>
                            <el-table-column header-align="center" label="平均分">
                                <template #default="scope">
                                    {{
            getaverage(scope.$index)
        }}</template>
                            </el-table-column>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- 专家意见 -->
            <div class="bg-white mt-[10px]">
                <BaseHead>专家意见</BaseHead>
                <div class="p-[10px]">
                    <el-table :data="expertTable" stripe style="width: 100%">
                        <el-table-column prop="reviewerName" header-align="center" label="专家名称" />
                        <el-table-column prop="reviewInfo" header-align="center" label="专家意见" />
                        <el-table-column prop="reviewResult" header-align="center" label="评审结果"
                            :formatter="formatpsjgId" />
                    </el-table>
                </div>
            </div>
            <p class="p-2">平均分：{{ getaverage(0) }}，有{{ passNum }}人建议通过，{{ noPassNum }}人不建议通过，{{ refuseReviewNum }}人拒绝评审
            </p>
            <template #footer>
                <div class="dialog-footer">
                    <div class="p-2">
                        <el-form :model="reviewForm">
                            <el-form-item label="">
                                <el-input v-model="reviewForm.reviewInfo" placeholder="评审意见" type="textarea" />
                            </el-form-item>
                            <el-form-item label="最终评审结果">
                                <el-radio-group v-model="reviewForm.result">
                                    <el-radio value="1">建议通过</el-radio>
                                    <el-radio value="2">不建议通过</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="operate-btns">
                        <!-- <el-button type="primary" v-if="executeType !='3'" @click="submitForm()">批准获奖</el-button>
                        <el-button type="primary" v-else @click="withdraw()">撤销获奖</el-button> -->
                        <el-button type="primary" @click="submitForm1()" v-if="ruleForm.honorState != '3'"
                            :loading="btnLoading">保存</el-button>
                        <el-button type="primary" @click="dialogVisibleMet">关闭</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { approveHonor, revokeHonor, updateHonorState } from "@/api/achievement/cghj"
import { ElMessage, ElMessageBox } from "element-plus";
import _ from "lodash";
const dialogVisible = defineModel();
const ruleForm = reactive({

})
const props = defineProps({
    executeType: String,
})
const reviewForm = reactive({
    reviewInfo: '',
    result: '1',
})

const reviewTableData = ref([])
const averageArr = ref([])
const expertTable = ref([])
const passNum = ref(0)
const noPassNum = ref(0)
const refuseReviewNum = ref(0)

const psjgList = ref([{
    code: "noPass",
    name: '不建议通过'
}, {
    code: "pass",
    name: '建议通过'
}, {
    code: "refuseReview",
    name: '拒绝评审'
}])

const formatpsjgId = (row, column, cellValue, index) => {
    console.log(cellValue, 'cellValue')
    if (cellValue == null && row.reviewStatus == 'refuseReview') {
        return '拒绝评审'
    }
    if (psjgList.value.length && cellValue) {
        return psjgList.value.find(item => item.code == cellValue) ? psjgList.value.find(item => item.code == cellValue).name : ''
    } else {
        return ''
    }
}

const submitForm = () => {
    let params = {
        reviewResult: 'pass',
        id: ruleForm.id
    }
    approveHonor(params).then(res => {
        if (res.code == 200) {
            emit('callBack', "")
            dialogVisible.value = false;
            ElMessage.success('转入成功')
        }
    })
}
const btnLoading = ref(false)
const submitForm1 = () => {
    let params = {
        honorState: reviewForm.result,
        id: ruleForm.id,
        reviewInfo: reviewForm.reviewInfo,
    }
    btnLoading.value = true;
    updateHonorState(params).then(res => {
        if (res.code == 200) {
            emit('callBack', "")
            dialogVisible.value = false;
            ElMessage.success('保存成功')
        }
        btnLoading.value = false;
    })
}



const withdraw = () => {
    let params = {
        reviewResult: 'noPass',
        id: ruleForm.id
    }
    revokeHonor(params).then(res => {
        if (res.code == 200) {
            emit('callBack', "")
            dialogVisible.value = false;
            ElMessage.success('转入成功')
        }
    })
}

const emit = defineEmits(['callBack']);
const ininDate = () => {
    Object.assign(ruleForm, {

    })
    Object.assign(reviewForm, {
        reviewInfo: '',
        result: 'pass',
    })
    reviewTableData.value = []
    averageArr.value = []
    expertTable.value = []
    passNum.value = 0
    noPassNum.value = 0
    refuseReviewNum.value = 0
}
const handleClose = (done) => {
    ininDate()
    done()
}

const dialogVisibleMet = () => {
    dialogVisible.value = false;
}
const isJSON = (str) => {
    if (typeof str === 'string') {
        try {
            const obj = JSON.parse(str);
            return typeof obj === 'object' && obj !== null;
        } catch (e) {
            return false;
        }
    }
    return false;
}
const getRuleForm = (i) => {
    for (const key in i) {
        ruleForm[key] = i[key];
    }
    expertTable.value = _.cloneDeep(ruleForm.allExpertReviewVOS);
    passNum.value = expertTable.value.filter(item => item.reviewResult == 'pass').length
    noPassNum.value = expertTable.value.filter(item => item.reviewResult == 'noPass').length
    refuseReviewNum.value = expertTable.value.filter(item => item.reviewStatus == 'refuseReview').length
    if (i.reviewStandardVOS && i.reviewStandardVOS.length > 0) {
        ruleForm.reviewStandardVOS = i.reviewStandardVOS.map(item => {
            if (isJSON(item.lvl2Names)) {
                return {
                    name: item.name,
                    id: item.id,
                    lvl2Names: JSON.parse(item.lvl2Names),
                    lvl2Marks: item.lvl2Marks.split(',').map(item => ({ value: item, score: null }))
                }
            } else {
                return {
                    name: item.name,
                    id: item.id,
                    lvl2Names: item.lvl2Names.split(',').map(item => ({ value: item })),
                    lvl2Marks: item.lvl2Marks.split(',').map(item => ({ value: item, score: null }))
                }
            }

        })
        reviewTableData.value = i.reviewStandardVOS.map(item => {
            return {
                name: item.name,
                id: item.id,
                standardMark: item.standardMark,
                lvl2Marks: item.lvl2Marks.split(',').map(item => ({ value: item, score: null }))
            }
        })
        averageArr.value = i.reviewStandardVOS.map((item, index) => {
            let sum = 0;
            let num = 0;
            if (i.allExpertReviewVOS && i.allExpertReviewVOS.length) {
                i.allExpertReviewVOS.forEach(item1 => {
                    if (item1.reviewResultVOs && item1.reviewResultVOs.length) {
                        sum += item1.reviewResultVOs[index].reviewMark
                        num++
                    }

                })
                return Number((sum / num).toFixed(0))
            } else {
                return 0
            }
        })
        if (i.allExpertReviewVOS && i.allExpertReviewVOS.length) {
            ruleForm.allExpertReviewVOS.forEach(item1 => {
                if (item1.reviewResultVOs && item1.reviewResultVOs.length) {
                    item1.reviewResultVOs.unshift({
                        reviewMark: item1.reviewResultVOs.map(item => item.reviewMark).reduce((a, b) => a + b).toFixed(2)
                    });
                }

            })
        }
        averageArr.value.unshift(averageArr.value.reduce((a, b) => a + b))
        reviewTableData.value.forEach(item => {
            item.standardMark = Number(item.lvl2Marks.map(item => {
                return Number(item.value)
            }).reduce((a, b) => a + b).toFixed(2))
        });
        reviewTableData.value.unshift({
            name: '合计',
            standardMark: reviewTableData.value.map(item => item.standardMark).reduce((a, b) => a + b)

        });

    }
    reviewForm.reviewInfo = ruleForm.reviewInfo
    ruleForm.reviewResult == 'pass' ? reviewForm.result = '1' : ruleForm.reviewResult == 'noPass' ? reviewForm.result = '2' : '';

    console.log(ruleForm, 'ruleForm')
    console.log(reviewTableData, 'reviewTableData')
}
const getaverage = (index) => {
    return averageArr.value[index] || 0;
}

defineExpose({
    getRuleForm
})
</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>
<style lang="scss">
.gdlable {
    width: 140px;
}
</style>